//
//  HDHTMLParser.swift
//  Excited
//
//  Created by X140Yu on 7/31/16.
//  Copyright © 2016 X140Yu. All rights reserved.
//

import Foundation
import Kanna


class HDHTMLParser {
    static func getRealName(html: String) -> String? {
        if let doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) {
            if let node = doc.at_xpath("//body//div//div//ul//li") {
                if let name = node.content {
                    return name
                }
            }
        }
        return nil
    }


    static func getScores(html: String, completion: (score: [HDScore]?, error: HDAPIError?) -> Void) {
        guard let doc = Kanna.HTML(html: html, encoding: NSUTF8StringEncoding) else { completion(score: nil, error: .ParseError); return }
        let node = doc.xpath("//table[@class='ui_table ui_table_hover ui_table_striped ui_table_style02']").first
        let classes = node?.xpath("tr[@class='t_con']")
        var retArray = Array<HDScore>()
        classes?.forEach({ (element) in

            let score = HDScore()

            // 2015-2016 第二学期
            let yearAndTermString = self.parseOneSectionForScoreObjct(element.xpath("td[2]"), trim: false)
            let arr = yearAndTermString.characters.split{$0 == " "}.map(String.init)
            if arr.count == 2 {
                // 2015-2016
                score.schoolYear = arr[0]
                // 第二学期
                score.term = arr[1]
            } else {
                score.schoolYear = ""
                score.term = ""
            }

            // 1412018026
            score.cid = self.parseOneSectionForScoreObjct(element.xpath("td[3]"))
            // 大学英语A（Ⅳ）
            score.name = self.parseOneSectionForScoreObjct(element.xpath("td[4]"))
            // 通识必修
            score.type = self.parseOneSectionForScoreObjct(element.xpath("td[5]"))
            // 必修课
            score.property = self.parseOneSectionForScoreObjct(element.xpath("td[6]"))
            // 2.5
            // 如果重复考过这门课几次，会造成学分重复，eg. 2.52.5 需要处理一下下
            score.credit = self.parseOneSectionForScoreObjct(element.xpath("td[7]"))
            // 这里做一个假设，前三个字符就是学分 =W=
            if score.credit.characters.count > 3 {
                let index = score.credit.startIndex.advancedBy(2)
                score.credit = score.credit.substringToIndex(index)
            }
            // 62
            score.score = self.parseOneSectionForScoreObjct(element.xpath("td[8]"))
            // 初修
            score.studyMethod = self.parseOneSectionForScoreObjct(element.xpath("td[9]"))
            // 缺考
            score.remark = self.parseOneSectionForScoreObjct(element.xpath("td[10]"))
            
//            debugPrint(score.schoolYear)
//            debugPrint(score.term)
//            debugPrint(score.cid)
//            debugPrint(score.name)
//            debugPrint(score.type)
//            debugPrint(score.property)
//            debugPrint(score.credit)
//            debugPrint(score.score)
//            debugPrint(score.studyMethod)
//            debugPrint(score.remark)

            retArray.append(score)
        })
        completion(score: retArray, error: nil)
    }
    
    static private func parseOneSectionForScoreObjct(obj: XPathObject, trim: Bool = true) -> String {
        switch obj {
        case .NodeSet(let node):
            if let text = node.text {
                if trim {
                    return text.trim()
                }
                return text
            }
            break
        default:
            return ""
        }
        return ""
    }
}

private extension String {
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }
}
